﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Common
{
    /// <summary>
    /// array数组方法扩展
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ArrayHelper<T>
    {
        /// <summary>
        /// Merges the specified source array.
        /// </summary>
        /// <param name="sourceArray">The source array.</param>
        /// <returns></returns>
        /// <remarks>将多维数组合并成一维数组,并且过滤重复的</remarks>
        public static T[] Merge(T[][] sourceArray, bool isDistinct)
        {

            if (sourceArray == null)
            {
                return null;
            }

            int length = 0;
            int p = 0;
            T[] target;

            for (int i = 0; i < sourceArray.Length; i++)
            {
                T[] t = sourceArray[i];

                if (t != null)
                {
                    length += t.Length;
                }

            }

            target = new T[length];

            for (int i = 0; i < sourceArray.Length; i++)
            {
                T[] t = sourceArray[i];
                if (t != null)
                {
                    t.CopyTo(target, p);
                    p += t.Length;
                }
            }
            if(isDistinct)
            {
                target = Distinct(target);
            }
            
            return target;
        }
        /// <summary>
        /// Merges the specified source array.
        /// </summary>
        /// <param name="sourceArray">The source array.</param>
        /// <returns></returns>
        public static T[] Merge(T[][] sourceArray)
        {
           return Merge(sourceArray,false);
            
        }

        private static T[] Distinct(T[] target)
        {
            List<T> listTarget = new List<T>();
            foreach (T t in target)
            {
                foreach (T tt in listTarget)
                {
                    if (t.Equals(tt))
                    {
                        goto end;//有相同的结束本次循环
                    }

                }
                listTarget.Add(t);//没有相同的,添加
            end:
                ;
            }
            target = listTarget.ToArray();
            return target;
        }

    }
}
